package com.zxs.config;

import lombok.Data;
import net.bytebuddy.description.field.FieldDescription;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;


@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config>{

	public AgeRoutePredicateFactory() {
		super(Config.class);
	}

	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("minAge","maxAge");
	}

	@Override
	public Predicate<ServerWebExchange> apply(AgeRoutePredicateFactory.Config config) {
		return exchange -> {
			String ageStr = exchange.getRequest().getQueryParams().getFirst("age");
			if(!StringUtils.isEmpty(ageStr)){
				int age = new Integer(ageStr);
				return age >= config.getMinAge() && age <= config.getMaxAge();
			}
			return false;
		};
	}
	// 定义在使用断言时传入的参数
	@Data
	 static class Config {
		private int minAge;
		private int maxAge;
	}
}